import React from 'react'
import PropTypes from 'prop-types'
import {Form, Input, Modal, Select} from 'antd'

const { Option } = Select
const FormItem = Form.Item
const { TextArea } = Input

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

const modal = ({
  item = {},
  onOk,
  nodes,
  form: {
    getFieldDecorator,
    validateFields,
    getFieldsValue,
  },
  ...modalProps
}) => {
  const handleOk = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      const data = {
        ...getFieldsValue(),
      }
      if (item.id) {
        data.id = item.id
      }
      onOk(data)
    })
  }

  const modalOpts = {
    ...modalProps,
    onOk: handleOk,
  }

  return (
    <Modal {...modalOpts}>
      <Form layout="horizontal">
        {item.id && <FormItem label="编号" hasFeedback {...formItemLayout}>
          {item.id}
        </FormItem>}
        <FormItem label="角色名" hasFeedback {...formItemLayout}>
          {getFieldDecorator('name', {
            initialValue: item.name,
            rules: [
              {
                required: true,
              },
            ],
          })(<Input />)}
        </FormItem>
        <FormItem label="数据权限" hasFeedback {...formItemLayout}>
          {getFieldDecorator('dataLevel', {
            initialValue: item.dataLevel,
            rules: [
              {
                required: true,
              },
            ],
          })(<Select>
            <Option key="gender_0" value="0">个人</Option>
            <Option key="gender_1" value="1">学院</Option>
            <Option key="gender_2" value="2">全部</Option>
          </Select>)}
        </FormItem>
        <FormItem label="节点权限" hasFeedback {...formItemLayout}>
          {getFieldDecorator('nodeIds', {
            initialValue: item.nodeIds,
          })(<Select
            mode="multiple"
          >
            {nodes.map(d => <Option key={d.id} value={d.id}>{d.title}</Option>)}
          </Select>)}
        </FormItem>
        <FormItem label="备注" hasFeedback {...formItemLayout}>
          {getFieldDecorator('remark', {
            initialValue: item.remark,
          })(<TextArea />)}
        </FormItem>
      </Form>
    </Modal>
  )
}

modal.propTypes = {
  form: PropTypes.object.isRequired,
  item: PropTypes.object,
  nodes: PropTypes.array,
  onOk: PropTypes.func,
}

export default Form.create()(modal)
